<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <el-dialog v-model="props.addVisible" :title="props.row?.id ? '编辑模板' : '新增模板'" width="500" @close="cancel">
    <div class="data_detail">
      <el-form ref="tempFormRef" :model="formData" size="small" label-width="100px" :rules="rules">
        <el-row>
          <el-col :span="24">
            <el-form-item label="模板名称" prop="templateName">
              <el-input v-model="formData.templateName" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="选择模型" prop="configId">
              <!-- <el-select v-model="formData.configId" placeholder="请选择模型" @change="getTableList($event)">
                <el-option v-for="item in modelNameList" :key="item.id" :label="item.modelName" :value="item.id"></el-option>
              </el-select>   -->
              <el-input v-model="formData.configName" readonly>
                <template #append>
                  <el-link type="primary" @click="gotoChoose">选择</el-link>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="业务场景" prop="businessId">
              <!-- <el-select style="width: 480px" v-model="formData.businessId" clearable placeholder="请选择" @change="getSystemList($event, true)">
                <el-option v-for="item in businessList" :label="item.name" :value="item.id" :key="item.id"></el-option>
              </el-select> -->
              <el-input :disabled="true" v-model="formData.businessSceneName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="业务系统" prop="businessSystemId">
              <!-- <el-select v-model="formData.businessSystemId" filterable clearable placeholder="请选择" @change="getSystemInfo">
                <el-option v-for="item in systemList" :label="item.name" :value="item.id" :key="item.id"></el-option>
              </el-select> -->
              <el-input :disabled="true" v-model="formData.businessSystemName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="要素库类型" prop="databaseType">
              <!-- <el-cascader style="width: 100%" v-model="formData.databaseType" :options="props.typeOptions" :props="cascaderProp"></el-cascader> -->
              <el-input :disabled="true" v-model="formData.databaseTypeName"></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24" v-if="databaseSubTypeList.length > 0">
            <el-form-item label="要素库子类型">
              <el-select v-model="formData.databaseSubtype" placeholder="请选择要素库子类型" @change="getModelData($event, true)">
                <el-option v-for="(item, index) in databaseSubTypeList" :key="index" :label="databaseSubTypeList[index]" :value="databaseSubTypeList[index]"></el-option>
              </el-select>  
            </el-form-item>
          </el-col> -->

          <el-col :span="24">
            <el-form-item label="描述">
              <el-input v-model="formData.templateDescription" type="textarea" :rows="3" placeholder="请描述创建此模板的目的和意义"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- <div class="table_data">
        <h3>请从以下要素库模型中的字段中选择本次建立的数据模板字段：</h3>
        <el-table ref="tableRef" :data="tableList" row-key="modelingConfigFieldId" @selection-change="handleSelectionChange">
          <el-table-column prop="fieldName" label="字段名"></el-table-column>
          <el-table-column prop="fieldChineseName" label="字段中文名"></el-table-column>
          <el-table-column prop="fieldType" label="字段类型"></el-table-column>
          <el-table-column prop="fieldLength" label="长度"></el-table-column>
        </el-table>
      </div> -->
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button size="small" @click="cancel"> 取消 </el-button>
        <el-button size="small" type="primary" @click="save"> 保存 </el-button>
      </div>
    </template>
  </el-dialog>
  <ModelChoose v-if="dialogVisible" :dialogVisible="dialogVisible" @handleEvent="handleEvent" />
</template>
<script name="AddTemplate" setup>
import ModelChoose from '@/components/ModelChoose';
import { saveDatabaseTemplate, getDatabaseTemplateDetail } from '@/api/system/template/index';
import { getElementModel, getModelDetail } from '@/api/metaData/model.ts';
import { getBusinessSystemList } from '@/api/businessSystem';
import { getTreeList } from '@/api/databaseManagement';
const props = defineProps(['addVisible', 'typeOptions', 'businessAll', 'row', 'enumList', 'databaseTypeList']);
const emit = defineEmits(['handleEvent']);
//tableList
const tableList = ref([]);
const enumList = ref([]);
const selectionList = ref([]);
//数据库详情
const dataBaseInfo = ref(null);
//数据表
const tables = ref(null);
// 查询参数
const queryData = ref([]);
// 页码对象
const pageNumObj = ref({});
const businessList = ref([]);
const systemList = ref([]);
const businessAll = ref([]);
const typeOptions = ref([]);
const tempFormRef = ref();
const cascaderProp = {
  expandTrigger: 'hover',
  emitPath: false,
  label: 'databaseName',
  value: 'id'
};
const formData = ref({
  templateName: '',
  templateDescription: '',
  configId: '',
  configName: ''
});
const rules = reactive({
  // businessId: [
  //   { required: true, message: '请选择业务场景', trigger: 'change' },
  // ],
  //   databaseType: [{ required: true, message: '请选择要素库类型', trigger: 'change' }],
  // businessSystemId: [
  //   { required: true, message: '请选择业务系统', trigger: 'blur' },
  // ],
  configId: [{ required: true, message: '请选择模型', trigger: 'change' }],
  templateName: [{ required: true, message: '请选择输入模板名称', trigger: 'blur' }]
});

const dialogVisible = ref(false);

const gotoChoose = () => {
  dialogVisible.value = true;
};
const handleEvent = (prop) => {
  if (prop.type == 'sure') {
    console.log(prop);
    const { modelName, id, versionNumber } = prop.modelInfo;
    getModelDetail({ id }).then((parentRes) => {
      if (parentRes.code === 200) {
        formData.value.databaseType = parentRes.data.databaseTypeId;
        formData.value.databaseTypeName = parentRes.data.databaseTypeName;
        formData.value.businessId = parentRes.data.sceneId;
        formData.value.businessSceneName = parentRes.data.sceneName;
        formData.value.businessSystemId = parentRes.data.systemId;
        formData.value.businessSystemName = parentRes.data.systemName;
      }
    });
    formData.value.configName = modelName;
    formData.value.configId = id;
    formData.value.versionNumber = versionNumber;
  }
  dialogVisible.value = false;
};
const getBusinessList = async () => {
  // await getBusinessSystemList({
  //   pageNum: 1,
  //   pageSize: 9999
  // }).then(res => {
  //   businessAll.value = res.rows;
  //   businessList.value = res.rows.filter(item => item.type == 0)
  // })
  businessList.value = props.businessAll.filter((item) => item.type == 0);
};
const getSystemList = (val, reset) => {
  if (reset) {
    formData.value.businessSystemId = '';
    formData.value.businessSystemName = '';
  }
  if (val) {
    systemList.value = props.businessAll.filter((item) => item.parentId == val && item.type == 1);
    formData.value.businessSceneName = businessList.value.find((item) => item.id == val).name;
  }
};
const getSystemInfo = (val) => {
  if (val) {
    formData.value.businessSystemName = systemList.value.find((item) => item.id == val).name;
  }
};
const queryTreeMenu = () => {
  getTreeList({ name: '' }).then((res) => {
    if (res) {
      typeOptions.value = res || [];
    }
  });
};
// 取消
const cancel = () => {
  emit('handleEvent', { type: 'cancel' });
};
// 保存
const save = () => {
  tempFormRef.value.validate((valid) => {
    if (valid) {
      let param = {
        id: props?.row?.id,
        ...formData.value
      };
      saveDatabaseTemplate(param).then((res) => {
        if (res.code === 200) {
          ElMessage({ showClose: true, message: `保存成功！`, type: 'success' });
          emit('handleEvent', { type: 'success' });
        } else {
          ElMessage({ showClose: true, message: `保存失败！`, type: 'warning' });
        }
      });
    }
  });
};
// 模板字段选择
const handleSelectionChange = (val) => {
  selectionList.value = val;
};
const getDetail = (id) => {
  getDatabaseTemplateDetail(id).then((res) => {
    if (res) {
      formData.value = res.data;
      if (formData.value.businessId) {
        getSystemList(formData.value.businessId, false);
      }
    }
  });
};
onMounted(async () => {
  // getTemplateInfo();
  // await getModuleConfigData();
  // getSingleTemplateData();
  await getBusinessList();
  // queryTreeMenu();
  props?.row?.id && getDetail(props?.row?.id);
});
</script>
<style lang="scss" scoped>
.data_detail {
  font-size: 12px;
  .basic {
    .title {
      background: #fafafa;
      height: 20px;
      line-height: 20px;
      font-weight: 600;
    }
    .basic_item {
      margin-top: 10px;
      > span:nth-child(2) {
        color: #909399;
      }
    }
    .split {
      width: 100%;
      height: 1px;
      background: #f4f4f4;
      margin-top: 10px;
    }
    .rows {
      margin-top: 10px;
      display: flex;
      justify-content: space-between;
      .row_item {
        width: 33%;
        > span:nth-child(2) {
          color: #909399;
        }
      }
    }
  }
  .data_view {
    margin-top: 20px;
    .title {
      background: #fafafa;
      height: 20px;
      line-height: 20px;
      font-weight: 600;
      display: flex;
      align-items: center;
      .view {
        margin-left: 10px;
        cursor: pointer;
      }
    }
  }
  .table_data {
    margin-top: 20px;
    .pagenation {
      display: flex;
      justify-content: end;
      margin-top: 10px;
    }
  }
}
</style>
